package weixin.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.appengine.api.fetchurl.FetchUrlServiceFactory;

public class HttpUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	// private static MultiThreadedHttpConnectionManager connectionManager = new
	// MultiThreadedHttpConnectionManager();
	// private static HttpClient httpClient = new HttpClient(connectionManager);

	public static String post(String url, Map<String, String> datas) {
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		NameValuePair[] data = null;
		if (datas != null) {
			int paramSize = datas.size();
			data = new NameValuePair[paramSize];
			int i = 0;
			Iterator<Entry<String, String>> it = datas.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, String> entry = it.next();
				data[i++] = new NameValuePair(entry.getKey(), entry.getValue());
			}
		}
		postMethod.setRequestBody(data);// 将表单的值放入postMethod中
		try {
			HttpConnectionManagerParams managerParams = httpClient
					.getHttpConnectionManager().getParams();
			managerParams.setConnectionTimeout(30000); // 设置连接超时时间(单位毫秒)
			managerParams.setSoTimeout(120000); // 设置读数据超时时间(单位毫秒)
			int statusCode = httpClient.executeMethod(postMethod);// 执行postMethod
			// HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
			if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
					|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {// 301或者302
				Header locationHeader = postMethod
						.getResponseHeader("location");// 从头中取出转向的地址
				String location = null;
				if (locationHeader != null) {
					logger.info("The page was redirected to:"
							+ locationHeader.getValue());
				} else {
					logger.error("Location field value is null.");
				}
			} else if (statusCode == HttpStatus.SC_OK) {
				return postMethod.getResponseBodyAsString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String post1(String url, Map<String, String> datas) {
		return FetchUrlServiceFactory.getFetchUrlService().post(url, datas);
	}

	public static String get1(String url, Map<String, String> datas) {
		StringBuilder sb = new StringBuilder(100);
		if (datas != null && datas.size() > 0) {
			Iterator<Entry<String, String>> it = datas.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, String> entry = it.next();
				if (sb.length() > 0) {
					sb.append("&");
				}
				sb.append(entry.getKey()).append("=").append(entry.getValue());
			}
		}
		return FetchUrlServiceFactory.getFetchUrlService().get(
				url + (sb.length() > 0 ? "?" + sb.toString() : ""));
	}

	public static String get(String url, Map<String, String> datas) {
		HttpClient httpClient = new HttpClient();
		StringBuilder sb = new StringBuilder(100);
		if (datas != null && datas.size() > 0) {
			Iterator<Entry<String, String>> it = datas.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, String> entry = it.next();
				if (sb.length() > 0) {
					sb.append("&");
				}
				sb.append(entry.getKey()).append("=").append(entry.getValue());
			}
		}
		GetMethod getMethod = new GetMethod(url
				+ (sb.length() > 0 ? "?" + sb.toString() : ""));
		try {
			HttpConnectionManagerParams managerParams = httpClient
					.getHttpConnectionManager().getParams();
			managerParams.setConnectionTimeout(30000); // 设置连接超时时间(单位毫秒)
			managerParams.setSoTimeout(120000); // 设置读数据超时时间(单位毫秒)
			int statusCode = httpClient.executeMethod(getMethod);// 执行postMethod
			// HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
			if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
					|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {// 301或者302
				Header locationHeader = getMethod.getResponseHeader("location");// 从头中取出转向的地址
				String location = null;
				if (locationHeader != null) {
					logger.info("The page was redirected to:"
							+ locationHeader.getValue());
				} else {
					logger.error("Location field value is null.");
				}
			} else if (statusCode == HttpStatus.SC_OK) {
				return getMethod.getResponseBodyAsString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static void main(String[] args) {
		String url = "https://api.weixin.qq.com/cgi-bin/token";
		Map<String, String> datas = new HashMap<String, String>();
		datas.put("grant_type", "client_credential");
		// datas.put("appid", AppID);
		// datas.put("secret", Appsecret);
		System.out.println(get1(url, datas));
	}
}
